import { useDispatch, useSelector } from "react-redux"
import { useEffect, useRef } from "react"
import type { RootState } from "@/types/store"
import { Dialog } from "antd-mobile"
import { useHistory } from "react-router-dom"


export const useInitialState = <KeyName extends keyof RootState>(action: () => void, stateName: KeyName) => {
  const dispatch = useDispatch()
  const state = useSelector((state: RootState) => state[stateName])
  const actionRef = useRef(action) 
  useEffect(() => {
    dispatch(actionRef.current())
  }, [dispatch]) 
  return state 
}


export const useAuthSet = () => {
  const token = useSelector((state: RootState) => state.login.token) 
  const history = useHistory<{ from: string }>()
  useEffect(() => {
    if (!token) {
      const handler = Dialog.show({
        title: "温馨提示",
        content: "亲，检测到您未登录，如需继续操作，需要进行去登录注册",
        actions: [
          [
            {
              key: "cancel",
              text: "去登录",
              onClick: () => {
                history.push("/login", {
                  from: history.location.pathname, 
                }) 
              },
            },
            {
              key: "confirm",
              text: "放弃操作",
              style: {
                color: "var(--adm-color-weak)",
              },
              onClick: () => {
                handler.close() 
              },
            },
          ],
        ],
      })
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
  return !!token
}


export const useResetRedux = <KeyName extends keyof RootState>(stateName: KeyName) => {
  const dispatch = useDispatch()
  useEffect(() => {
    return () => {
      dispatch({ type: "reset", payload: stateName })
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
}
